#!/usr/bin/env python
# -*- coding: utf-8 -*-
# For sister Deng Hong
# Description: sqlite3 support
# Date: 2018-04-15

import sqlite3

# 数据库访问对象，负责ReferenceItem数据到数据库的存储


class ReferenceDAO():
    def __init__(self, source, db_path):
        self.db_path = db_path
        self.conn = sqlite3.connect(self.db_path)
        self.source = source
        self.conn.execute("create table IF NOT EXISTS referenceitems (id integer primary key, name varchar(20), title text NULL, author text NULL, institution text NULL, abstract text NULL, doi text NULL, keywords text NULL, category text NULL, year text NULL, issue text NULL, journal text NULL, issn text NULL, url text NULL)")

    def add(self, refItem):
        t = (self.source, refItem.title, refItem.authors, refItem.institutions, refItem.abstract, refItem.doi,
             refItem.keywords, refItem.category, refItem.year, refItem.issue, refItem.journal, refItem.issn, refItem.url,)
        self.conn.execute(
            "insert into referenceitems (name, title, author, institution, abstract, doi, keywords, category, year, issue, journal, issn, url) values (?,?,?,?,?,?,?,?,?,?,?,?,?)", t)

    # 是否已经存在相同记录：按照name和标题检索
    def exists(self, refItem):
        cur = self.conn.cursor()
        cur.execute("SELECT * FROM referenceitems where name=? and title=?",
                    (self.source, refItem.title,))
        rows = cur.fetchall()
        if rows and rows > 0:
            return True
        return False

    def commit(self):
        self.conn.commit()

    def close(self):
        self.conn.close()
